
package com.csc440.team2.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.csc440.team2.SmilConstants;
import com.csc440.team2.communication.CommunicationManager;
import com.csc440.team2.database.entities.FolderType;
import com.csc440.team2.database.entities.Message;
import com.csc440.team2.smil.SMILComponent;
import com.csc440.team2.smil.SMILMessage;
import com.csc440.team2.smil.SMILReadException;


public class Components extends Activity
{
    private SMILMessage message;


    @Override
    public void onCreate(Bundle savedIntanceState)
    {
        super.onCreate(savedIntanceState);
        setContentView(R.layout.components_layout);

        final Bundle bundle = getIntent().getExtras();

        if (bundle != null)
        {
            // get the current message
            message = (SMILMessage) bundle.getSerializable(SmilConstants.MESSAGE);

            Button editButton = (Button) findViewById(R.id.AddItems);
            editButton.setOnClickListener(new OnClickListener()
            {
                public void onClick(View v)
                {
                    /*
                     * Forward to layout class to add more items.
                     */
                    Intent in = new Intent(Components.this, CreateSMILLayout.class);
                    in.putExtra(SmilConstants.MESSAGE, message);
                    Components.this.startActivityForResult(in, 1);
                }

            });

            Button sendButton = (Button) findViewById(R.id.Send);
            sendButton.setOnClickListener(new OnClickListener()
            {
                public void onClick(View v)
                {
                    /*
                     * try to send the message, if it works save it and send the
                     * user back to the main menu
                     */
                    if (sendMessage())
                    {
                        saveMessage(FolderType.SENT);
                        Intent in = new Intent(Components.this, MainMenu.class);
                        Components.this.startActivityForResult(in, 1);
                        finish();
                    }
                }
            });

            Button previewButton = (Button) findViewById(R.id.Preview);
            previewButton.setOnClickListener(new OnClickListener()
            {

                public void onClick(View v)
                {
                    /*
                     * Send to SMIL Player to be previewed
                     */
                    Intent myIntent = new Intent(v.getContext(), SMILPlayer.class);
                    myIntent.putExtra(SmilConstants.MESSAGE, message);
                    startActivity(myIntent);
                }

            });

            Button saveButton = (Button) findViewById(R.id.Save);
            saveButton.setOnClickListener(new OnClickListener()
            {
                public void onClick(View v)
                {
                    /*
                     * Save message as a draft and forward user to main menu
                     */
                    saveMessage(FolderType.DRAFT);
                    Intent in = new Intent(Components.this, MainMenu.class);
                    Components.this.startActivityForResult(in, 1);
                    finish();
                }
            });

            ListView lv = (ListView) findViewById(R.id.ComponentsList);

            List<SMILComponent> list = getComponents(message);
            if (list.size() == 0)
                lv.setAdapter(new ArrayAdapter<String>(this, R.layout.components, new String[] {
                    "No components to display"
                }));
            else
                lv.setAdapter(new ArrayAdapter<SMILComponent>(this, R.layout.components, getComponents(message)));
        }
    }


    /*
     * Saves the current SMIL Message to the database using the provided type
     */
    private void saveMessage(FolderType type)
    {
        try
        {
            // create a database message object from the SMIL message's XML
            Message dbMessage;
            dbMessage = new Message(message.getXml(), type, true, "");

            // attempt to save and log the results
            if (dbMessage.save(this))
                Log.i("Save", "Message Saved");
            else
                Log.i("Save", "Failed to save message");
        }
        catch (SMILReadException e)
        {
            Log.e("Save", "Could not save message", e);
        }
    }


    /*
     * Sends the message to its intended receiver
     */
    private boolean sendMessage()
    {
        // get the receiver to send the message to
        EditText toBox = (EditText) findViewById(R.id.ToBox);
        String reciever = toBox.getText().toString();

        // if receiver is entered, attempt to send the message
        if (reciever != null && !"".equals(reciever))
        {
            CommunicationManager.sendSMILMessage(message, reciever);

            // receive was successful
            return true;
        }
        else
            return false;
    }


    /*
     * utility method to get the list of components from a message
     */
    private List<SMILComponent> getComponents(SMILMessage message)
    {
        return message.getComponentList();
    }


    @Override
    protected void onSaveInstanceState(Bundle bundle)
    {
        bundle.putSerializable(SmilConstants.MESSAGE, message);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (data != null)
        {
            ListView lv = (ListView) findViewById(R.id.ComponentsList);

            // get the updated message from the activity return.
            SMILMessage returnedMessage = (SMILMessage) data.getExtras().get(SmilConstants.MESSAGE);
            message = returnedMessage;

            // update the list view with the list of components on the current
            // message
            lv.setAdapter(new ArrayAdapter<SMILComponent>(this, R.layout.components, getComponents(message)));
        }
    }

}
